﻿using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynCRMMessagingIntegration.Common
{
    public class MessageProcessorFactory
    {
        public static BaseMessageProcessor GetProcessor(string xmlMessage, ITracingService tracingService)
        {
            if (string.IsNullOrEmpty(xmlMessage))
                throw new ArgumentNullException("XML Message is null or empty, so a Message Process cannot be instanciated");

            string messageName = xmlMessage.GetFirstElementName();
            string messageProcessorFullName = string.Format("DynCRMMessagingIntegration.Common.{0}{1}", messageName, "Processor");
            tracingService.Trace("New Processor is going to instanciated. Name: {0}", messageProcessorFullName);
            Type myTypeObj = Type.GetType(messageProcessorFullName);
            if (myTypeObj != null)
            {
                BaseMessageProcessor processor = (BaseMessageProcessor)Activator.CreateInstance(myTypeObj, xmlMessage);
                tracingService.Trace("Processor instance has been created correctly. ProcessorName: {0}", messageProcessorFullName);
                return processor;
            }
            else
                tracingService.Trace("Type has not been found for processor {0}", messageProcessorFullName);

            return null;
        }
    }
}
